package com.pilipili.serverapi.controller.video;


import com.pilipili.common.Exception.BusinessRuntimeException;
import com.pilipili.common.controller.AbstractController;
import com.pilipili.common.controller.CommonResult;
import com.pilipili.common.controller.PageCommResult;
import com.pilipili.serverapi.ErrorCode;
import com.pilipili.serverapi.collection.service.CollectionService;
import com.pilipili.serverapi.video.dto.req.VideoSearchDto;
import com.pilipili.serverapi.video.dto.req.VideoUploadDto;
import com.pilipili.serverapi.video.dto.resp.VideoSearchResultDto;
import com.pilipili.serverapi.video.entity.Task;
import com.pilipili.serverapi.video.entity.Video;
import com.pilipili.serverapi.video.service.TaskService;
import com.pilipili.serverapi.video.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 视频管理接口
 *
 * @author chen.guosheng
 */
@Api(description = "视频管理接口")
@RestController
@RequestMapping("/serverapi/video")
public class VideoController extends AbstractController {

    private static final Logger LOG = LoggerFactory.getLogger(VideoController.class);

    @Autowired
    private VideoService videoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private CollectionService collectionService;

    @ApiOperation(value = "投稿视频")
    @ApiImplicitParam(name = "Token", value = "用于验证登录的token", paramType = "header", dataType = "string")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @RequiresPermissions("video")
    public CommonResult<Object> upload(@Valid VideoUploadDto videoUploadDto,
                                       @RequestParam(value = "videoOriFile", required = true) MultipartFile videoOriFile,
                                       BindingResult bindingResult) throws IOException {
        LOG.info(" access /serverapi/video/upload videoUploadDto {} ", videoUploadDto);
        if (bindingResult.hasErrors()) {
            throw new BusinessRuntimeException(ErrorCode.PRAMERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        if(videoService.exits("title", videoUploadDto.getTitle(), Video.class)){
            throw new BusinessRuntimeException(ErrorCode.VIDOEO_TITLE_EXIST);
        }
        if(videoService.exits("videoOri", videoUploadDto.getUserId()+"_"+videoOriFile.getOriginalFilename(), Video.class)){
            throw new BusinessRuntimeException(ErrorCode.VIDEO_ORI_EXIST);
        }
//        LOG.info(videoOriFile.getName());
//        String[] f = videoOriFile.getOriginalFilename().split("\\.");
//        LOG.info(f[0]);
        videoService.uploadVideo(videoUploadDto, videoOriFile);
        return successResultWithEmptyResult();
    }


    @ApiOperation(value = "批量删除视频")
    @RequiresPermissions("video")
    @ApiImplicitParam(name="Token", value="用于验证登录的token", paramType="header",dataType="string")
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public  CommonResult<Object> batchDelete(@RequestParam("videoIds") List<Long> videoIds) {
        LOG.info(" access /serverapi/video/batchDelete videoIds {} ", videoIds);
        videoService.batchDelete(videoIds);
        List<String> taskIds = new ArrayList<>();
        for(Long videoId : videoIds){
            List<Task> tasks = taskService.findByVideoId(videoId);
            for(Task task : tasks){
                taskIds.add(task.getTaskId());
            }
        }
        taskService.batchDelete(taskIds);
        collectionService.batchDeleteByVideoIds(videoIds);
        return this.successResultWithEmptyResult();
    }

    @ApiOperation(value = "多条件搜索视频")
    @ApiImplicitParam(name = "Token", value = "用于验证登录的token", paramType = "header", dataType = "string")
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public PageCommResult<VideoSearchResultDto> search(@Valid @RequestBody VideoSearchDto videoSearchDto, BindingResult bindingResult) {
        LOG.info(" access /serverapi/video/search videoSearchDto {} ", videoSearchDto);
        if (bindingResult.hasErrors()) {
            throw new BusinessRuntimeException(ErrorCode.PRAMERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        return videoService.search(videoSearchDto);
    }

    @ApiOperation(value = "审核已完成转码的视频")
    @ApiImplicitParam(name = "Token", value = "用于验证登录的token", paramType = "header", dataType = "string")
    @RequestMapping(value = "/videoAudit", method = RequestMethod.POST)
    @RequiresPermissions("videoAudit")
    public CommonResult<Object> videoAudit(@RequestParam("videoId") Long videoId, @RequestParam("auditState") Long auditState){
        LOG.info(" access /serverapi/video/videoAudit videoId auditState {} ", videoId, auditState);
        Video video = videoService.find(videoId);
        if(video != null)
        if(video.getTransState() == 0){
            throw new BusinessRuntimeException(ErrorCode.VIDEO_AUDIT_ERROR);
        }
        videoService.videoAudit(videoId, auditState);
        return successResultWithEmptyResult();
    }

    @ApiOperation(value = "验证视频审核权限")
    @ApiImplicitParam(name="Token", value="用于验证登录的token", paramType="header",dataType="string")
    @RequiresPermissions("videoAudit")
    @RequestMapping(value = "/videoAudit/testAuth", method = RequestMethod.POST)
    public PageCommResult<Object> testAuth() {
        LOG.info(" access /serverapi/video/testAuth");
        return this.successPageResultWithEmptyResult();
    }

}
